package reflect

import (
	"gvm/native/basic"
	"gvm/rtda"
	"gvm/rtda/heap"
)

func RegisterReflection() (className string, methods []*basic.NaMethod) {
	return "sun/reflect/Reflection", []*basic.NaMethod{
		{
			"getCallerClass",
			"()Ljava/lang/Class;",
			getCallerClass,
		}, {
			"getClassAccessFlags",
			"(Ljava/lang/Class;)I",
			getClassAccessFlags,
		},
	}
}

// public static native Class<?> getCallerClass();
func getCallerClass(jFrame *rtda.JFrame) {
	// top0 is sun/reflect/Reflection
	// top1 is the caller of getCallerClass()
	// top2 is the caller of method
	callerFrame := jFrame.JThread().GetJFrames()[2] // todo
	callerClass := callerFrame.Method().Class().JClass()
	jFrame.OperandStack().PushRef(callerClass)
}

// public static native int getClassAccessFlags(Class<?> type);
func getClassAccessFlags(jFrame *rtda.JFrame) {
	vars := jFrame.LocalVars()
	_type := vars.GetRef(0)

	goClass := _type.Extra().(*heap.Klass)
	flags := goClass.AccessFlags()

	stack := jFrame.OperandStack()
	stack.PushInt(int32(flags))
}
